/**
 *    Copyright 2012 Geensoft S.A.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/
package ar.com.greensoft.neosystem.admin.users;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import ar.com.greensoft.jeecommons.web.jsf.util.JSFMenuUtil;
import ar.com.greensoft.neosystem.crm.web.beans.NavigationConstants;
import ar.com.greensoft.neosystem.dao.AuthorityDao;
import ar.com.greensoft.neosystem.dao.DaoException;
import ar.com.greensoft.neosystem.dao.UserDao;
import ar.com.greensoft.neosystem.model.Authority;
import ar.com.greensoft.neosystem.model.User;
import ar.com.greensoft.neosystem.util.ApplicationRoles;

/**
 * @author Jorge E. Villaverde
 *
 */
@ViewScoped
@ManagedBean
public class EditUserBean implements Serializable, ApplicationRoles, NavigationConstants {

	@Inject
	private Logger logger;
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Inject
	private UserDao userDao;
	@Inject
	private AuthorityDao authorityDao;
	
	/**
	 * Editing User
	 */
	private User user;
	
	/**
	 * Available Authorities
	 */
	private List<String> authorities;
	
	/**
	 * User authorities
	 */
	private List<String> selectedAuthorities;
	
    /**
     * Cancel View
     */
    protected String cancelView;
    
    /**
     * Return View
     */
    protected String persistReturnView;
    
    private String username;
	
	@PostConstruct  
	public void init() { 
		authorities = new ArrayList<String>();
		authorities.add(ROLE_ADMIN);
		authorities.add(ROLE_USER);
		
		clearData();  
	} 
	
	public void clearData() {
		if(user == null)
			this.selectedAuthorities = null;
	}
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String showEdit(){
		if(this.username == null)
			throw new IllegalStateException("user not set");

		FacesContext ctx = FacesContext.getCurrentInstance();
		cancelView = ctx.getViewRoot().getViewId();
		
		try {
			user = userDao.findUserByUsername(username);
			selectedAuthorities = new ArrayList<String>();
			List<Authority> userAuthorities = authorityDao.findByUser(user);
			
			for(Authority authority : userAuthorities){
				selectedAuthorities.add(authority.getAuthority());
			}
			
			return JSFMenuUtil.buildMenuPath(ADMIN_PATH, "users", EDIT_ACTION);
		} catch (DaoException e) {
		}
		return null;
	}

	public String editUser(){
		if(this.user == null)
			throw new IllegalStateException("user not set");
		
		if(logger.isLoggable(Level.FINE))
			logger.fine("Saving User: " + user.getUsername());
		
		try {
			userDao.merge(user);
			// Revoke all Authorities
			for(Authority authority : user.getAuthorities()){
				userDao.removeAuthority(user, authority.getAuthority());
			}
			// Grant Selected
			for(String authorityName : selectedAuthorities){
				Authority authority = new Authority();
				authority.setUser(user);
				authority.setAuthority(authorityName);
				userDao.addAuthority(authority);
			}
		} catch (DaoException e) {
			logger.severe(e.getMessage());
		}
		
		if(logger.isLoggable(Level.FINE))
			logger.fine("User " + user.getUsername() + " SAVED.");
		
		if(persistReturnView != null && !persistReturnView.isEmpty())
			return persistReturnView + JSFMenuUtil.JSF_REDIRECT_ESCAPED;
		return showEdit();		
	}
	
	public String cancel() {
		if(cancelView != null && !cancelView.isEmpty()) 
			return cancelView + JSFMenuUtil.JSF_REDIRECT_ESCAPED;
		return showEdit();		
	}
	
	public String getCancelView() {
		return cancelView;
	}

	public void setCancelView(String cancelView) {
		this.cancelView = cancelView;
	}

	public String getPersistReturnView() {
		return persistReturnView;
	}

	public void setPersistReturnView(String persistReturnView) {
		this.persistReturnView = persistReturnView;
	}

	public List<String> getAuthorities() {
		return authorities;
	}

	public void setAuthorities(List<String> authorities) {
		this.authorities = authorities;
	}

	public List<String> getSelectedAuthorities() {
		return selectedAuthorities;
	}

	public void setSelectedAuthorities(List<String> selectedAuthorities) {
		this.selectedAuthorities = selectedAuthorities;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}	
}
